package com.ys.controller.web.mall;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ys.controller.api.mall.ApiInterTmGiftGivenController;
import com.ys.controller.api.mall.ApiInterTmGiftUseController;
import com.ys.entity.finance.TcwAccountCountForUser;
import com.ys.entity.mall.TmCate;
import com.ys.entity.mall.TmGift;
import com.ys.entity.mall.TmGiftUse;
import com.ys.entity.mall.TmGoods;
import com.ys.entity.shiro.LoginUser;
import com.ys.entity.sys.TsUserInfo;
import com.ys.enume.sys.TsUserInfoEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.ImgcodeService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.W;

import lombok.AllArgsConstructor;
import lombok.Data;

@Controller
@RequestMapping("/web/mall")
public class WebMallController {
	
	@Autowired
	private CommonApiService<TmGiftUse> commonApiService;
    @Autowired
    private ImgcodeService imgcodeService;
	
	/*
	 * 商城首页
	 */
//	@RequiresPermissions("tmGoods:view")
	@GetMapping("/index")
	public String index(Model model,
			String loginName, String pass){
		
		loginName = "admin";
		pass = "7e79f98921a75735381dac811b7bcd0f";
		
		String loginUserId = ShiroUtils.getUserId();
		if (loginUserId == null || loginUserId.length() == 0) {
			if (loginName != null && loginName.length() > 0 && pass != null && pass.length() > 0) {

				TsUserInfo tsUserInfo = new TsUserInfo().setUserId(loginName).setUserPassWord(pass).queryFirst();
				if (tsUserInfo != null) {
					imgcodeService.doAuthAfterLogin(tsUserInfo);
				}
			} else {
				return "/login";
			}
		} else {
			if (loginName != null && loginName.length() > 0 && pass != null && pass.length() > 0 && !loginUserId.equals(loginName)) {

				TsUserInfo tsUserInfo = new TsUserInfo().setUserId(loginName).setUserPassWord(pass).queryFirst();
				if (tsUserInfo != null) {
					imgcodeService.doAuthAfterLogin(tsUserInfo);
				}
			}
		}
		
		// 最近上新
		List<IndexDto.LatestDto> latestArr = new ArrayList<IndexDto.LatestDto>();
		List<TmGoods> listGoodsLatest = new TmGoods().setOrderby("A.CreateTime desc").setPage(0).setSize(5).queryList();
		for(TmGoods entity : listGoodsLatest) {
			Long id = entity.getId();
			String img = entity.getImg();
			String code = entity.getCode();
			String name = entity.getName();
			String amount = entity.getAmount().toString();
			latestArr.add(new IndexDto.LatestDto(id, img, code, name, amount));
		}
		
		// 类目数组
		List<IndexDto.CateDto> cateArr = new ArrayList<IndexDto.CateDto>();
		List<TmCate> listTmCate = new TmCate().setOrderby("A.id asc").setPage(0).setSize(4).queryList();
		for(TmCate tmCate : listTmCate) {
			Long id = tmCate.getId();
			String img = tmCate.getImg();
			cateArr.add(new IndexDto.CateDto(id, img));
		}
		
		IndexDto dto = new IndexDto(latestArr, cateArr);
		model.addAttribute("dto", dto);

		return "mall/index";
	}
	@Data
	@AllArgsConstructor
	public static class IndexDto{
		private List<LatestDto> latestArr; // 最近上新5条
		private List<CateDto> cateArr; // 类目列表
		
		@Data
		@AllArgsConstructor
		public static class LatestDto {
			private Long id; // 礼品ID
			private String img; // 礼品封面图
			private String code; // 礼品编码
			private String name; // 礼品名称
			private String amount; // 礼品价格
		}
		
		@Data
		@AllArgsConstructor
		public static class CateDto {
			private Long id; // 类目ID
			private String img; // 类目封面图
		}
	}
	
	
	
	/*
	 * 商品详情页
	 */
	@RequiresPermissions("tmGoods:view")
	@GetMapping("/toDetailGoods")
	public String toDetailGoods(Model model, String code){
		
		if (code == null || code.length() == 0) {
			return W.error(model, "商品编码不能为空");
		}
		
		TmGoods entity = new TmGoods().setCode(code).queryFirst();
		if (entity == null) {
			return W.error(model, "商品不存在");
		}
		
		
		Long id = entity.getId();
		String name = entity.getName();
		String img = entity.getImg();
		String detail = entity.getDetail();
		BigDecimal salePrice = entity.getAmount();
		Integer stockNum = entity.getStockNum();
		Integer saleNum = 0;
		
		ToDetailGoodsDto dto = new ToDetailGoodsDto(id, name, code, img, detail, salePrice, stockNum, saleNum);
		model.addAttribute("dto", dto);
		
		return "mall/toDetailGoods";
	}
	@Data
	@AllArgsConstructor
	public static class ToDetailGoodsDto{
		private Long id; // 字段ID
		private String name; // 字段名称
		private String code; // 编码
		private String img; // 封面图
		private String detail; // 商品详情
		private BigDecimal salePrice; // 售价
		private Integer stockNum; // 库存
		private Integer saleNum; // 销量
	}
	
	/*
	 * 商品购买页
	 */
	@RequiresPermissions("tmGoods:view")
	@GetMapping("/toBuy")
	public String toBuy(Model model, Long id){
		
		if (id == null) {
			return W.error(model, "ID不能为空");
		}
		
		TmGoods entity = new TmGoods().setId(id).queryFirst();
		if (entity == null) {
			return W.error(model, "礼品不存在");
		}
		
		LoginUser loginUser = ShiroUtils.getLoginUser();
		String userId = loginUser.getUserId();
		TcwAccountCountForUser tcwAccountCountForUser = new TcwAccountCountForUser().setUserId(userId).queryFirst();
		
		
		String code = entity.getCode();
		String name = entity.getName();
		String img = entity.getImg();
		BigDecimal salePrice = entity.getAmount();
		Integer stockNum = entity.getStockNum();
		Integer saleNum = 0;
		
		BigDecimal point = tcwAccountCountForUser.getPoint();
		ToBuyDto dto = new ToBuyDto(point, id, name, code, img, salePrice, stockNum, saleNum);
		model.addAttribute("dto", dto);
		
		return "mall/toBuy";
	}
	@Data
	@AllArgsConstructor
	public static class ToBuyDto{
		private BigDecimal point; // 积分余额
		private Long id; // 字段ID
		private String name; // 字段名称
		private String code; // 编码
		private String img; // 封面图
		private BigDecimal salePrice; // 售价
		private Integer stockNum; // 库存
		private Integer saleNum; // 销量
	}
	
	/**
	 * 个人中心
	 */
	@GetMapping("/userCenter")
	public String userCenter(Model model,
			String loginName, String pass){
		
		loginName = "admin";
		pass = "7e79f98921a75735381dac811b7bcd0f";
		
		String loginUserId = ShiroUtils.getUserId();
		if (loginUserId == null || loginUserId.length() == 0) {
			if (loginName != null && loginName.length() > 0 && pass != null && pass.length() > 0) {

				TsUserInfo tsUserInfo = new TsUserInfo().setUserId(loginName).setUserPassWord(pass).queryFirst();
				if (tsUserInfo != null) {
					imgcodeService.doAuthAfterLogin(tsUserInfo);
				}
			} else {
				return "/login";
			}
		} else {
			if (loginName != null && loginName.length() > 0 && pass != null && pass.length() > 0 && !loginUserId.equals(loginName)) {

				TsUserInfo tsUserInfo = new TsUserInfo().setUserId(loginName).setUserPassWord(pass).queryFirst();
				if (tsUserInfo != null) {
					imgcodeService.doAuthAfterLogin(tsUserInfo);
				}
			}
		}
		
		LoginUser loginUser = ShiroUtils.getLoginUser();
		String userId = loginUser.getUserId();
		TsUserInfo entity = new TsUserInfo().setUserId(userId).queryFirst();
		TcwAccountCountForUser account = new TcwAccountCountForUser().setUserId(userId).queryFirst();
		String userName = entity.getUserName();
		
		String gradeName = TsUserInfoEnum.UserGrade.getName(entity.getUserGrade());
		String nextGradeName = TsUserInfoEnum.UserGrade.getName(entity.getUserGrade() + 1);
		BigDecimal currentPointNeed = TsUserInfoEnum.UserGrade.getPoint(entity.getUserGrade());
		BigDecimal nextPointNeed = TsUserInfoEnum.UserGrade.getPoint(entity.getUserGrade() + 1);
		BigDecimal point = account.getPoint();
		BigDecimal nextPointGap = account.getPoint().subtract(nextPointNeed);
		UserCenterDto dto = new UserCenterDto(userId, userName, gradeName, currentPointNeed, nextGradeName, nextPointNeed, point, nextPointGap);
		
		model.addAttribute("dto", dto);
		return "mall/userCenter";
	}
	@Data
	@AllArgsConstructor
	private static class UserCenterDto{
		private String userId;
		private String userName; // 名称
		private String gradeName; // 等级名称
		private BigDecimal currentPointNeed; // 当前等级学分要求
		private String nextGradeName; // 下一个等级名称
		private BigDecimal nextPointNeed; // 下一级学分要求
		private BigDecimal point; // 可用学分
		private BigDecimal nextPointGap; // 升下一级还差多少学分
	}
	
	/*
	 * 礼品使用页
	 */
	@GetMapping("/toUse")
	public String toUse(Model model, String code){
		
		if (code == null || code.length() == 0) {
			return W.error(model, "礼品编码不能为空");
		}

		LoginUser loginUser = ShiroUtils.getLoginUser();
		String userId = loginUser.getUserId();
		TmGift entity = new TmGift()
				.setCode(code)
				.setUserId(userId)
				.queryFirst();
		if (entity == null) {
			return W.error(model, "礼品不存在");
		}

		try {
			String bid = commonApiService.getCommonNextBid(ApiInterTmGiftUseController.MENU_ID);
			ToUseDto dto = new ToUseDto(code, bid);
			model.addAttribute("dto", dto);
		} catch (Exception e) {
			e.printStackTrace();
			
			return W.error(model, "数据有误，请联系客服");
		}
		
		return "mall/toUse";
	}
	@Data
	@AllArgsConstructor
	public static class ToUseDto{
		private String code; // 编码
		private String bid; // 单号
	}
	
	/*
	 * 礼品转赠页
	 */
	@GetMapping("/toSend")
	public String toSend(Model model, String code){
		
		if (code == null || code.length() == 0) {
			return W.error(model, "礼品编码不能为空");
		}

		LoginUser loginUser = ShiroUtils.getLoginUser();
		String userId = loginUser.getUserId();
		TmGift entity = new TmGift()
				.setCode(code)
				.setUserId(userId)
				.queryFirst();
		if (entity == null) {
			return W.error(model, "礼品不存在");
		}

		try {
			String bid = commonApiService.getCommonNextBid(ApiInterTmGiftGivenController.MENU_ID);
			ToUseDto dto = new ToUseDto(code, bid);
			model.addAttribute("dto", dto);
		} catch (Exception e) {
			e.printStackTrace();
			
			return W.error(model, "数据有误，请联系客服");
		}
		
		return "mall/toSend";
	}
	@Data
	@AllArgsConstructor
	public static class ToSendDto{
		private String code; // 编码
		private String bid; // 单号
	}
}
